package com.arica.framework.mq.producer;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MQProducerConfiguration {

    public static final Logger LOGGER = LoggerFactory.getLogger(MQProducerConfiguration.class);

    @Value("${rocketmq.nameSrvAddr}")
    private String nameSrvAddr;

    @Value("${rocketmq.producer.group}")
    private String group;

    /**
     * 消息最大大小，默认4M
     */
    @Value("${rocketmq.producer.max-message-size}")
    private Integer maxMessageSize ;
    /**
     * 消息发送超时时间，默认3秒
     */
    @Value("${rocketmq.producer.send-message-timeout}")
    private Integer sendMsgTimeout;
    /**
     * 消息发送失败重试次数，默认2次
     */
    @Value("${rocketmq.producer.retry-times-when-send-failed}")
    private Integer retryTimesWhenSendFailed;

    @Bean
    public DefaultMQProducer getRocketMQProducer() throws Exception {

        if(StringUtils.isEmpty(this.group)){
            throw new RuntimeException("group is blank");
        }

        if (StringUtils.isEmpty(this.nameSrvAddr)) {
            throw new RuntimeException("nameServerAddr is blank");
        }

        DefaultMQProducer producer;
        producer = new DefaultMQProducer(this.group);

        producer.setNamesrvAddr(this.nameSrvAddr);
//        producer.setCreateTopicKey("AUTO_CREATE_TOPIC_KEY");

        //如果需要同一个jvm中不同的producer往不同的mq集群发送消息，需要设置不同的instanceName
        //producer.setInstanceName(instanceName);
        if(this.maxMessageSize!=null){
            producer.setMaxMessageSize(this.maxMessageSize);
        }
        if(this.sendMsgTimeout!=null){
            producer.setSendMsgTimeout(this.sendMsgTimeout);
        }
        //如果发送消息失败，设置重试次数，默认为2次
        if(this.retryTimesWhenSendFailed!=null){
            producer.setRetryTimesWhenSendFailed(this.retryTimesWhenSendFailed);
        }

        LOGGER.info("MQ 生产者初始化完成....");

//        try {
//            producer.start();
//
//            LOGGER.info(String.format("producer is start ! groupName:[%s],namesrvAddr:[%s]"
//                    , this.group, this.nameSrvAddr));
//        } catch (MQClientException e) {
//            LOGGER.error(String.format("producer is error {}"
//                    , e.getMessage(),e));
//            throw new RuntimeException(e);
//        }
        return producer;

    }
}
